﻿create PROCEDURE Sync.SP_LoanExecutionAttachments_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @LoanExecutionAttachments_Temp TABLE 
		(
			LoanExecutionAttachmentID UniqueIdentifier,
			[LoanExecutionID] uniqueidentifier,
				[Attachment] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @LoanExecutionAttachments_Temp 
	   SELECT	Tbl.Col.value('LoanExecutionAttachmentID[1]','uniqueidentifier') LoanExecutionAttachmentID,
                Tbl.Col.value('LoanExecutionID[1]', 'uniqueidentifier') [LoanExecutionID],
Tbl.Col.value('Attachment[1]', 'uniqueidentifier') [Attachment],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/LoanExecutionAttachments') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[LoanExecutionAttachments] ([LoanExecutionAttachmentID],[LoanExecutionID],[Attachment])
	SELECT t.[LoanExecutionAttachmentID],t.[LoanExecutionID],t.[Attachment]
	FROM  @LoanExecutionAttachments_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.LoanExecutionAttachments_Tracking s
        WHERE t.LoanExecutionAttachmentID = s.LoanExecutionAttachmentID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[LoanExecutionAttachments]
	SET [LoanExecutionAttachments].[LoanExecutionID] = t.[LoanExecutionID],[LoanExecutionAttachments].[Attachment] = t.[Attachment] 
	FROM [dbo].[LoanExecutionAttachments] s JOIN @LoanExecutionAttachments_Temp t 
    ON t.LoanExecutionAttachmentID = s.LoanExecutionAttachmentID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.LoanExecutionAttachments_Tracking r
				  WHERE t.LoanExecutionAttachmentID = r.LoanExecutionAttachmentID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[LoanExecutionAttachments]
    FROM @LoanExecutionAttachments_Temp t JOIN [dbo].[LoanExecutionAttachments] s
    ON t.LoanExecutionAttachmentID = s.LoanExecutionAttachmentID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











